package com.example.goodsmanagementcabinet.serialport;

import android.util.Log;

import com.aill.androidserialport.SerialPort;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static java.lang.Thread.sleep;

public class SerialPortConnect {
    public static SerialPortConnect serialPortConnect;
    private String lockKeyCode[] = new String[33];
    private String lockStates[] = new String[33];
    private String strOpenDoor = "5AA50A01";
    private String strReadCode = "5AA50A02";
    private String emptyCode = "000000000000000000";
    private FileOutputStream mOutputStream;
    private FileInputStream mInputStream;
    private SerialPort sp;
    private ReadThread mReadThread;
    private StringBuffer recevierType = new StringBuffer();
    private boolean isReadData = false;

    public static SerialPortConnect getInstance() {
        if (serialPortConnect == null) {
            serialPortConnect = new SerialPortConnect();
        }
        return serialPortConnect;
    }

    public String getKeyCode(int lockid) {
        String keyCode;
        keyCode = this.lockKeyCode[lockid];
        return keyCode;
    }

    public String getlockState(int lockid) {
        String keyCode;
        keyCode = this.lockStates[lockid];
        return keyCode;
    }

    public boolean connect(String device, int baud) {
        boolean con = false;
        try {
            sp = new SerialPort(new File("" + device), baud, 0);//这里写你要打开的串口和波特率
            Log.e("SerialPortConnect", "打开串口成功");
            mOutputStream = (FileOutputStream) sp.getOutputStream();
            mInputStream = (FileInputStream) sp.getInputStream();
            con = true;
            receviedData();
        } catch (Throwable tr) {
            con = false;
            Log.e("SerialPortConnect", "打开串口失败");
        }
        return con;
    }

    public void receviedData() {
        if (mReadThread == null) {
            mReadThread = new ReadThread();
            isReadData = true;
            mReadThread.start();
        }
        for (int i = 0;i<33;i++){
            lockKeyCode[i] = "FFFFFFFF";
            lockStates[i] = "00";
        }
    }


    private class ReadThread extends Thread {//接收线程
        byte[] buffer = new byte[14];

        @Override
        public void run() {
            super.run();
            while (isReadData) {
                int size;
                try {
                    if (mInputStream != null) {
                        size = mInputStream.read(buffer);//接收数据
                        if (size > 0) {
                            onDataReceived(buffer, size);
                            String receveData = bytesToHexString(buffer, size);
                            Log.e("SerialPortConnect", "receveData: " + receveData);
                            if (receveData.substring(0, 6).equals("5AA50A")) {
                                int loc = Integer.parseInt(receveData.substring(8, 10), 16);
                                String date = receveData.substring(14, 22);
                                String lockstate = receveData.substring(6, 8);
                                lockKeyCode[loc - 1] = date;
                                lockStates[loc - 1] = lockstate;
                                Log.e("SerialPortConnect", "标签号" + Arrays.toString(lockKeyCode));
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
    }

    public static String bytesToHexString(byte[] bArray, int length) {
        StringBuffer sb = new StringBuffer(length);
        String sTemp;
        for (int i = 0; i < length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    protected void onDataReceived(final byte[] buffer, final int size) {
        new Thread(new Runnable() {
            public void run() {
                recevierType.append(new String(buffer, 0, size));
            }
        });
    }


    public boolean sendData(String data) {
        boolean suf = false;
        if (sp != null) {
            try {
                mOutputStream.write(hexStringToBytes(data));//这里发送的是十六进制的数据
                Log.d("SerialPortConnect", data + "发送成功");
                suf = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Log.d("SerialPortConnect", "设备未连接");
        }
        return suf;
    }

    public static byte[] hexStringToBytes(String inputStr) {
        byte[] result = new byte[inputStr.length() / 2];
        for (int i = 0; i < inputStr.length() / 2; ++i)
            result[i] = (byte) (Integer.parseInt(inputStr.substring(i * 2, i * 2 + 2), 16) & 0xff);
        return result;
    }

    public void openLock(final int lockid) {
        String initType = strOpenDoor + integerToHexString(lockid) + emptyCode;
        sendData(initType);
    }

    public void readCode(int lockid) {
        String initType = strReadCode + integerToHexString(lockid) + emptyCode;
        sendData(initType);
    }

    /**
     * 将十进制整数转为十六进制数，并补位
     */
    public static String integerToHexString(int s) {
        String ss = Integer.toHexString(s);
        if (ss.length() % 2 != 0) {
            ss = "0" + ss;//0F格式
        }
        return ss.toUpperCase();
    }

}